
<script setup lang="ts">
import { ref, watch, onMounted, computed } from 'vue';
import { useImage } from '@/hooks';
import { useRouterPush } from '@/composables';
import { useNurseGoods } from '@/service';
import { hideLoading, showLoading } from '@tarojs/taro';
import { getServiceVisibleList } from '@/service/api/nurse_user';
import { list as listNurseDistance } from '@/service/api/nurse_distance';
import good from './good.vue';
import { getDict } from '@/service/api/dict';
import { IconFont } from '@nutui/icons-vue-taro'
import { localStg, PlatformUtils } from '@/utils';
import { useConfigStore } from '@/store';
import Taro from '@tarojs/taro';


const props = defineProps({
    hospital: {
        type: String,
        required: true
    }
});

// 四级分类数据结构
interface CategoryNode {
    id: string | number;
    pid: string | number;
    type_name: string;
    title?: string;
    key?: string;
    has_child?: number;
    children: CategoryNode[];
    // 商品属性
    pic?: string;
    goods_name?: string;
    unit?: string;
    price?: number;
}

interface DictItem {
    id?: string | number;
    itemValue: string | number;
    itemText: string;
}

// 分类数据
const typeList = ref<DictItem[]>([]); // 一级分类
const cateList2 = ref<CategoryNode[]>([]); // 二级分类
const cateList3 = ref<CategoryNode[]>([]); // 三级分类
const cateList4 = ref<CategoryNode[]>([]); // 四级分类

// 当前选中的分类
const act1 = ref<string | number>('2'); // 一级分类
const act2 = ref<string | number | undefined>(undefined); // 二级分类
const act3 = ref<string | number | undefined>(undefined); // 三级分类
const act4 = ref<string | number | undefined>(undefined); // 四级分类

const validate = ref<string>('0');

// 商品列表
const productList = ref<CategoryNode[]>([]);

const { getGoodsList, loadTreeChildrenNew } = useNurseGoods();


const configStore = useConfigStore();

onMounted(() => {
    // getDict("nurse_type").then((res: any) => {
    //     // res nurse type
    //     typeList.value = res;
    //     if (res && res.length > 0) {
    //         act1.value = res[1].itemValue;
    //         console.log('act1.value===', res);
    //     }
    // })

    getServiceVisibleList(props.hospital).then((res: any) => {
        // console.log('res===555==', res);
        if(res.success.records?.length == 0){
            Taro.showToast({
                title: "未配置一级分类",
                icon: "none"                
            })
            return
        }
        const record = res.success.records[0];
        // console.log(record, 'record ##### 😂 configStore ------')
        // 存入全局配置 store
        configStore.setFromRecord(record);
        // 从 store 读取控制 typeList 显示
        const ary = configStore.modeList.map((item: string, index: number) => ({
            itemText: configStore.modeTextList[index],
            itemValue: item
        }));
        typeList.value = ary;
        // console.log('typeList.value===', typeList.value);
    })
})

// 构建树形结构
function buildTree(records: any[]): CategoryNode[] {
    const map: Record<string | number, CategoryNode> = {};
    const roots: CategoryNode[] = [];
    
    // 首先创建所有项目的映射
    records.forEach(item => {
        map[item.id] = { ...item, children: [] };
    });

    // 然后通过分配子项给父项来构建树
    records.forEach(item => {
        const parent = map[item.pid];
        if (parent) {
            parent.children.push(map[item.id]);
        } else if (item.pid === '0') {
            roots.push(map[item.id]);
        }
    });

    return roots;
}

// 选择一级分类
const selectCategory = (categoryId: string | number) => {
    act1.value = categoryId;
};

// 选择二级分类
const selectSubCategory = (subCategoryId: string | number) => {
    act2.value = subCategoryId;
};

// 选择三级分类
const selectSonCategory = (sonCategoryId: string | number) => {
    act3.value = sonCategoryId;
};

// 选择四级分类
const selectGrandSonCategory = (grandSonCategoryId: string | number) => {
    act4.value = grandSonCategoryId;
};

// 获取二级分类数据
const getCate2Data = async () => {
    // act1.value
    const { error, success } = await getGoodsList({
        pid: '0',
        nurse_type: act1.value,
        hospital: props.hospital
    });
    
    if (!error && success) {
        cateList2.value = success;
        if (cateList2.value.length > 0) {
            const firstItem = cateList2.value[0];
            act2.value = (firstItem.key as string | number) || firstItem.id;
        } else {
            act2.value = undefined;
            cateList3.value = [];
            cateList4.value = [];
            productList.value = [];
        }
    }
};

// 获取三级分类数据
const getCate3Data = async () => {
    if (!act2.value) {
        cateList3.value = [];
        cateList4.value = [];
        productList.value = [];
        act3.value = undefined;
        act4.value = undefined;
        return;
    }
    
    const { error, success } = await loadTreeChildrenNew({ pid: act2.value as string });
    if (!error && success) {
        cateList3.value = success;
        if (cateList3.value.length > 0) {
            act3.value = cateList3.value[0].id;
        } else {
            act3.value = undefined;
            cateList4.value = [];
            productList.value = [];
            act4.value = undefined;
        }
    }
};

// 获取四级分类数据
const getCate4Data = async () => {
    if (!act3.value) {
        cateList4.value = [];
        productList.value = [];
        act4.value = undefined;
        return;
    }
    
    const { error, success } = await loadTreeChildrenNew({ pid: act3.value });
    if (!error && success) {
        cateList4.value = success;
        if (cateList4.value.length > 0) {
            act4.value = cateList4.value[0].id;
        } else {
            act4.value = undefined;
            productList.value = [];
        }
    }
};

// 获取商品列表
const getProductList = async () => {
    // console.log("产品列表===")
    // if (!act4.value) {
    //     productList.value = [];
    //     return;
    // }
    
    // const { error, success } = await loadTreeChildrenNew({ pid: act4.value });
    // if (!error && success) {
    //     productList.value = success;
    // }
};

// 监听分类变化
watch(
    () => act1.value,
    (newVal) => {
        getCate2Data();
        
        const obj:any = PlatformUtils.getDefaultHospital()
        // console.log("defaulthospital", obj)
        listNurseDistance({
            hospital: obj.name,
            type: newVal
        }).then((res: any) => {
            // console.log('res===777==', res);
            validate.value = res.success.records[0]?.validate || '0';
            // console.log("validate.value", validate.value)
            Taro.setStorageSync('typeLevel1', newVal);
            Taro.setStorageSync('hospitalName', obj.name);
        })
    }, {
        immediate: true
    }
);

watch(
    () => act2.value,
    () => {
        getCate3Data();
    }
);

watch(
    () => act3.value,
    () => {
        getCate4Data();
    }
);

watch(
    () => act4.value,
    () => {
        getProductList();
    }
);

const { toGoodsDetail } = useRouterPush();

const toDetail = (item: any) => {
    // toDetail
    toGoodsDetail({
        id: item.id,
        pic: item.pic,
        pname: item.goods_name,
        unit: item.serviceUnit || '1',//时长单位
        nurseType: String(act1.value),
        goods_type: '1',
        nurseTypeText: item.goods_name,
        menu1: String(act1.value),
    });
};


// const toDetail = (item: any) => {
//     // toDetail
//     toGoodsDetail({
//         id: item.id,
//         pic: item.pic,
//         pname: item.goods_name,
//         unit: item.unit,
//         nurseType: modelValue.value,
//         goods_type: '1',
//         nurseTypeText: item.goods_name
//     });
// };

// 暴露验证方法给父组件
defineExpose({
    getData: () => getCate2Data()
});
</script>

<template>
    <view class="h-full w-full">
        <!-- 一级分类 -->
        <nut-tabs v-model="act1" title-scroll title-gutter="20" size="large" background="#fff" class="w-full h-40px bg-#fff">
            <nut-tab-pane :title="item.itemText" :pane-key="item.itemValue" v-for="item in typeList" :key="item.id"></nut-tab-pane>
        </nut-tabs>
        
        <view class="w-full">
            <nut-empty v-if="!cateList2 || cateList2.length == 0" description="暂无数据"></nut-empty>
            <view class="h-315px flex">
                <!-- 左侧导航 -->
                <view class="w-[200rpx] h-full overflow-y-auto bg-#f8f8f8">
                    <view 
                        v-for="item in cateList2" 
                        :key="item.key || item.id" 
                        class="h-[80rpx] flex items-center justify-start text-[28rpx] px-[12rpx] border-b border-#eee"
                        :class="act2 === (item.key || item.id) ? 'bg-#fff text-#fa2c19 font-bold' : 'text-gray-500'"
                        @tap="selectSubCategory(item.key || item.id)"
                    >
                        {{ item.title || item.type_name }}
                    </view>
                </view>
                
                <!-- 右侧内容 -->
                <view class="flex-1 h-full overflow-y-auto bg-#fff p-[20rpx]">
                    <view v-if="cateList2.length > 0">
                        <!-- 三级分类 -->
                        <view v-if="cateList3.length > 0" class="mb-[30rpx] flex w-full overflow-x-auto">
                            <nut-button 
                                class="text-[32rpx] inline-block mr-[16rpx] mb-[16rpx]"
                                v-for="sonCategory in cateList3"
                                :type="act3 === sonCategory.id ? 'success' : 'default'"
                                plain
                                :key="sonCategory.id"
                                size="small"
                                @tap="selectSonCategory(sonCategory.id)"
                            >
                                {{ sonCategory.type_name }}
                            </nut-button>
                        </view>
                        <view v-else class="h-full">
                            <view class="flex-col-center h-full py-8">
                                <IconFont font-class-name="iconfont" class-prefix="icon" size="54" name="meiyoushuju" />
                                <view class="text-[28rpx] text-#999 mt-2">暂无数据</view>
                            </view>
                        </view>
                        
                        <!-- 四级分类 -->
                        <view v-if="cateList4.length > 0" class="mb-[30rpx]">
                            <good 
                                v-for="item2 in cateList4" 
                                :key="item2.id" 
                                :obj="item2" 
                                :validate="validate"
                                :src="useImage(item2.pic || '')"
                                @jump="toDetail(item2)" 
                            />
                        </view>
                        <NutEmpty v-else></NutEmpty>
                    </view>
                   
                </view>
            </view>
        </view>
    </view>
</template>

<style lang="scss">
.nut-tabs__titles-item {
    width: fit-content !important;
}
</style>
